package app

import (
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/mvc"
	"github.com/sirupsen/logrus"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"webapp/controller"
)

func InitIris() {
	app := iris.New()
	app.Logger().SetLevel("debug")
	app.Use(recover.New())
	app.Use(logger.New())

	// http 访问控制
	app.Use(cors.New(cors.Options{
		AllowedOrigins:  []string{"*"},
		AllowOriginFunc: nil,
		AllowedMethods:  []string{iris.MethodGet, iris.MethodPost, iris.MethodDelete, iris.MethodPut, iris.MethodOptions, iris.MethodOptions},
		AllowedHeaders:  []string{"*"},
		ExposedHeaders:  nil,
		// 预检请求有效期
		MaxAge:             600,
		AllowCredentials:   false,
		OptionsPassthrough: false,
		Debug:              false,
	}))

	//预检请求方法
	app.AllowMethods(iris.MethodOptions)

	app.Any("/", func(i iris.Context) {
		_, _ = i.HTML("<h1>hello world</h1>")
	})

	// 设置路由
	mvc.Configure(app.Party("/admin"), func(application *mvc.Application) {
		application.Party("/user").Handle(new(controller.UserController))
	})

	server := &http.Server{Addr: ":" + "9098"}
	handleSignal(server)

	err := app.Run(iris.Server(server), iris.WithConfiguration(iris.Configuration{
		IgnoreServerErrors:                nil,
		DisableStartupLog:                 false,
		DisableInterruptHandler:           false,
		DisablePathCorrection:             false,
		DisablePathCorrectionRedirection:  false,
		EnablePathEscape:                  false,
		EnableOptimizations:               true,
		FireMethodNotAllowed:              false,
		DisableBodyConsumptionOnUnmarshal: false,
		DisableAutoFireStatusCode:         false,
		TimeFormat:                        "2006-01-02 15:04:05",
		Charset:                           "UTF-8",
	}))

	if err != nil {
		os.Exit(-1)
	}
}

func handleSignal(server *http.Server) {
	c := make(chan os.Signal)
	signal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)

	go func() {
		s := <-c
		logrus.Infof("got signal [%s], exiting now", s)
		if err := server.Close(); nil != err {
			logrus.Errorf("server close failed: " + err.Error())
		}
		//
		//simple.CloseDB()
		//
		//logrus.Infof("Exited")
		os.Exit(0)
	}()
}

//func main() {
//	InitIris()
//}
